import lodash from 'lodash';
import moment from 'moment';
import { summaryHistogram } from '../services/summary-controller';
import { fmtDateTime } from '../utils/fmt'

export default {
  namespace: 'SummaryDiffModel',

  state: {
    queryParam: {
      index: undefined,
      // 图类型
      histogramPrefix: 'txh',
      // 开始时间 - 6天前
      startTime: moment().subtract(5, 'days').startOf('day'),
      // 时间间隔 YYYY-MM-DD HH:mm:ss
      interval: '1D',
      diffCount: 6,
    },
    intervalList: [
      { value: '1H', label: '1小时' },
      { value: '3H', label: '3小时' },
      { value: '5H', label: '5小时' },
      { value: '12H', label: '12小时' },
      { value: '1D', label: '1天' },
      { value: '3D', label: '3天' },
      { value: '5D', label: '5天' },
      { value: '7D', label: '7天' },
      { value: '15D', label: '15天' },
    ],
    diffCountList: [
      { value: 2, label: '2次' },
      { value: 4, label: '4次' },
      { value: 6, label: '6次' },
      { value: 8, label: '8次' },
      { value: 10, label: '10次' },
      { value: 12, label: '12次' },
    ],

    diffData: [],
  },

  effects: {
    *findDiffData({ payload }, { select, call, put }) {
      const { currentSysName } = yield select(state => state.GlobalEnumModel);
      let { queryParam } = yield select(state => state.SummaryDiffModel);
      queryParam = { ...queryParam, index: currentSysName, ...payload };
      // 处理 queryParam
      const intervalUnit = queryParam.interval.charAt(queryParam.interval.length - 1);
      const intervalNum = lodash.toNumber(queryParam.interval.substring(0, queryParam.interval.length - 1));
      if (intervalUnit === 'H') {
        queryParam.startTime = moment(queryParam.startTime).startOf('hour');
      }
      if (intervalUnit === 'D') {
        queryParam.startTime = moment(queryParam.startTime).startOf('day');
      }
      // 查询数据
      const diffData = [];
      let min = null;
      let max = null;
      for (let i = 0; i < queryParam.diffCount; i++) {
        const { histogramPrefix, index } = queryParam;
        if (min === null) {
          min = queryParam.startTime
        } else {
          min = max;
        }
        max = moment(min).add(intervalNum, intervalUnit === 'H' ? 'hours' : 'days');
        const histogramData = yield call(summaryHistogram, { histogramPrefix, max: fmtDateTime(max), min: fmtDateTime(min), index });
        diffData.push({ label: `${fmtDateTime(min)} ~ ${fmtDateTime(max)}`, data: histogramData });
      }
      // 保存数据
      yield put({ type: 'save', payload: { queryParam, diffData } });
      yield put({ type: 'GlobalEnumModel/save', payload: { currentSysName: queryParam.index } });
    },
  },

  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
